import { Exclude } from 'class-transformer';
import {
  BeforeInsert,
  BeforeUpdate,
  Column,
  CreateDateColumn,
  Entity,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from 'typeorm';
import * as bcrypt from 'bcrypt';
import { IsEmpty, IsPhoneNumber } from 'class-validator';

@Entity('custom_user', { schema: 'shop' })
export class User {
  constructor(partial: Partial<User>) {
    Object.assign(this, partial);
  }

  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 50, comment: '用户名' })
  username: string;

  @Column({ select: false })
  @Exclude()
  password: string;

  @Column('varchar', {
    name: 'phone_number',
    default: null,
    comment: '手机号，可选',
  })
  @IsPhoneNumber('CH', { message: '请输入正确的手机号' })
  phoneNumber: string;

  @Column('varchar', {
    name: 'role',
    length: 10,
    default: 'customer',
    comment: '用户角色; 默认是 user, 可以升级为 vip 角色的账号',
  })
  role: string;

  @Column({
    name: 'is_delete',
    type: 'tinyint',
    default: 1,
    select: false,
    comment: '逻辑删除标识',
  })
  @Exclude()
  isDelete: number;

  @CreateDateColumn({ name: 'create_time', comment: '注册时间' })
  createTime: Date;

  @UpdateDateColumn({ name: 'modify_time', comment: '更改时间' })
  modifyTime: Date;

  @BeforeInsert()
  async encryptPassword() {
    this.password = bcrypt.hashSync(this.password, 10);
  }

  @BeforeUpdate()
  async updatePassword() {
    this.password = bcrypt.hashSync(this.password, 10);
  }
}
